package com.example.whatrubbish.controller;

import com.example.whatrubbish.utils.Constants;
import com.example.whatrubbish.utils.JsonResult;
import com.example.whatrubbish.utils.UploadFileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${app.fileUrl:https://www.layoom.top/rubbish/imgs/}")
    String FILE_URL;

    @Autowired
    UploadFileUtil uploadFileUtil;

    @PostMapping("/upload")
    public JsonResult upload(HttpServletRequest request,
                             @RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return new JsonResult(Constants.STATUS_FAIL, "文件不能为空");
        }
        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1);
        String fileName = uploadFileUtil.upload(file, fileExt);
        return new JsonResult(Constants.STATUS_SUCCESS, "上传成功", FILE_URL.concat(fileName));
    }
}
